package commands;

import indexes.BattingIndex;
import indexes.PlayerIDIndex;
import indexes.PlayerNameIndex;

import java.io.IOException;
import java.util.List;

import util.BattingBPlusRecord;
import util.BattingCSVParser;
import util.BattingDatabaseFile;
import util.BattingRecord;
import util.DatabaseFile;
import util.PlayerLogger;
import util.Record;
/**
 * Opens the given file, adds the batting records to the
 * batting database, adds a record to the battingindex for
 * each id.
 * @author xclite
 *
 */
public class ImportBattingCommand extends Command
{
    /**
     * Typical constructor.
     * @param arguments
     */
    protected ImportBattingCommand( List<String> arguments )
    {
        super( arguments );
    }

    @Override
    public boolean execute(
        PlayerIDIndex idIndex,
        PlayerNameIndex nameIndex,
        PlayerLogger logger,
        DatabaseFile database, BattingIndex battingIndex, BattingDatabaseFile battingDatabase ) throws IOException
    {
        
        logger.write(super.getDivider() + "\n");
        logger.write( "Command: import_batting " + getArguments().get(0) + "\n\n");
        List<BattingRecord> imported = battingDatabase.importBattingRecords(getArguments().get(0));
        String currentKeyBeingAdded = null;
        long currentOffset;
        BattingRecord record;
        int recordIndex = 0;
        int numIds = 0;
        currentKeyBeingAdded = imported.get(0).getId();
        currentOffset = imported.get(0).getOffset();
        while (recordIndex < imported.size())
        {
            //This information is the info for the BPlusTree entry - we only put the first item of a sequence of the same id in the tree.
            record = imported.get(recordIndex);
            
            
            if (!currentKeyBeingAdded.equals(record.getId()))
            {
                battingIndex.add(new BattingBPlusRecord(currentKeyBeingAdded, currentOffset));
                currentKeyBeingAdded = record.getId();
                currentOffset = record.getOffset();
                ++numIds;
            }
            ++recordIndex;
        }
        //add the last run of records.
        battingIndex.add(new BattingBPlusRecord(currentKeyBeingAdded, currentOffset));
        
        logger.write("Imported: " + imported.size() + " records and added " + numIds + " entries to batting index.\n");
        return true;
    }

}
